package com.xunshibao.core.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;

import com.xunshibao.core.security.SecurityUtils;

public class XunshibaoArgumentResolver implements WebArgumentResolver {

	@Override
	public Object resolveArgument(MethodParameter methodParameter,
			NativeWebRequest webRequest) throws Exception {
		if (methodParameter.getParameterType().equals(SessionUser.class)) {
            return webRequest.getAttribute(SecurityUtils.USER_KEY, RequestAttributes.SCOPE_SESSION);
        } else if (methodParameter.getParameterType().equals(IpAddress.class)) {
            String ip = webRequest.getHeader("x-forwarded-for");
            if (ip == null) {
                ip = webRequest.getNativeRequest(HttpServletRequest.class).getRemoteAddr();
            }
            
            return new IpAddress(ip);
        }
        return UNRESOLVED;
	}

}
